using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.Build.Framework;
using System.IO;
using PerformanceDude.MSBuildProfiler;

namespace MSBuildProfiler
{
    public class MSBuildProfileFileLogger : ILogger
    {
        #region ILogger Members

        public void Initialize(IEventSource eventSource)
        {
            var profiler = new PerformanceDude.MSBuildProfiler.MSBuildProfiler(eventSource);
            profiler.ProfilerFinished += OnProfilerFinished;
        }

        private void OnProfilerFinished(Build build)
        {
            string logFile = null;
            if (_parameters != null)
            {
                var pars = _parameters.Split(new[] {';'});
                foreach (var par in
                    pars.Select(s => s.Split(new[] {'='})).Where(par => par.Length == 2).Where(par => par[0].Equals("file")))
                {
                    logFile = par[1];
                }
            }
            //If file param not found, default to build.snapshot.
            if (logFile == null)
            {
                logFile = ".\\build.snapshot";
            }
            using (var fileStream = new FileStream(logFile, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(fileStream, build);
            }
        }

        private string _parameters;

        public string Parameters
        {
            get { return _parameters; }
            set { _parameters = value; }
        }

        public void Shutdown()
        {
        }

        private LoggerVerbosity _verbosity;

        public LoggerVerbosity Verbosity
        {
            get { return _verbosity; }
            set { _verbosity = value; }
        }

        #endregion
    }
}